/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pp.persistance;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.pp.entites.Site;
import com.pp.entites.Evenement;
import com.pp.entites.Personnel;
import com.pp.persistance.exceptions.NonexistentEntityException;
import com.pp.persistance.exceptions.PreexistingEntityException;
import com.pp.persistance.exceptions.RollbackFailureException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author arnaud
 */
public class PersonnelJpaController implements Serializable {

    public PersonnelJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Personnel personnel) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (personnel.getEvenementList() == null) {
            personnel.setEvenementList(new ArrayList<Evenement>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Site idsite = personnel.getIdsite();
            if (idsite != null) {
                idsite = em.getReference(idsite.getClass(), idsite.getId());
                personnel.setIdsite(idsite);
            }
            List<Evenement> attachedEvenementList = new ArrayList<Evenement>();
            for (Evenement evenementListEvenementToAttach : personnel.getEvenementList()) {
                evenementListEvenementToAttach = em.getReference(evenementListEvenementToAttach.getClass(), evenementListEvenementToAttach.getEvenementPK());
                attachedEvenementList.add(evenementListEvenementToAttach);
            }
            personnel.setEvenementList(attachedEvenementList);
            em.persist(personnel);
            if (idsite != null) {
                idsite.getPersonnelList().add(personnel);
                idsite = em.merge(idsite);
            }
            for (Evenement evenementListEvenement : personnel.getEvenementList()) {
                Personnel oldIdpersonnelOfEvenementListEvenement = evenementListEvenement.getIdpersonnel();
                evenementListEvenement.setIdpersonnel(personnel);
                evenementListEvenement = em.merge(evenementListEvenement);
                if (oldIdpersonnelOfEvenementListEvenement != null) {
                    oldIdpersonnelOfEvenementListEvenement.getEvenementList().remove(evenementListEvenement);
                    oldIdpersonnelOfEvenementListEvenement = em.merge(oldIdpersonnelOfEvenementListEvenement);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findPersonnel(personnel.getId()) != null) {
                throw new PreexistingEntityException("Personnel " + personnel + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Personnel personnel) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Personnel persistentPersonnel = em.find(Personnel.class, personnel.getId());
            Site idsiteOld = persistentPersonnel.getIdsite();
            Site idsiteNew = personnel.getIdsite();
            List<Evenement> evenementListOld = persistentPersonnel.getEvenementList();
            List<Evenement> evenementListNew = personnel.getEvenementList();
            if (idsiteNew != null) {
                idsiteNew = em.getReference(idsiteNew.getClass(), idsiteNew.getId());
                personnel.setIdsite(idsiteNew);
            }
            List<Evenement> attachedEvenementListNew = new ArrayList<Evenement>();
            for (Evenement evenementListNewEvenementToAttach : evenementListNew) {
                evenementListNewEvenementToAttach = em.getReference(evenementListNewEvenementToAttach.getClass(), evenementListNewEvenementToAttach.getEvenementPK());
                attachedEvenementListNew.add(evenementListNewEvenementToAttach);
            }
            evenementListNew = attachedEvenementListNew;
            personnel.setEvenementList(evenementListNew);
            personnel = em.merge(personnel);
            if (idsiteOld != null && !idsiteOld.equals(idsiteNew)) {
                idsiteOld.getPersonnelList().remove(personnel);
                idsiteOld = em.merge(idsiteOld);
            }
            if (idsiteNew != null && !idsiteNew.equals(idsiteOld)) {
                idsiteNew.getPersonnelList().add(personnel);
                idsiteNew = em.merge(idsiteNew);
            }
            for (Evenement evenementListOldEvenement : evenementListOld) {
                if (!evenementListNew.contains(evenementListOldEvenement)) {
                    evenementListOldEvenement.setIdpersonnel(null);
                    evenementListOldEvenement = em.merge(evenementListOldEvenement);
                }
            }
            for (Evenement evenementListNewEvenement : evenementListNew) {
                if (!evenementListOld.contains(evenementListNewEvenement)) {
                    Personnel oldIdpersonnelOfEvenementListNewEvenement = evenementListNewEvenement.getIdpersonnel();
                    evenementListNewEvenement.setIdpersonnel(personnel);
                    evenementListNewEvenement = em.merge(evenementListNewEvenement);
                    if (oldIdpersonnelOfEvenementListNewEvenement != null && !oldIdpersonnelOfEvenementListNewEvenement.equals(personnel)) {
                        oldIdpersonnelOfEvenementListNewEvenement.getEvenementList().remove(evenementListNewEvenement);
                        oldIdpersonnelOfEvenementListNewEvenement = em.merge(oldIdpersonnelOfEvenementListNewEvenement);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = personnel.getId();
                if (findPersonnel(id) == null) {
                    throw new NonexistentEntityException("The personnel with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Personnel personnel;
            try {
                personnel = em.getReference(Personnel.class, id);
                personnel.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The personnel with id " + id + " no longer exists.", enfe);
            }
            Site idsite = personnel.getIdsite();
            if (idsite != null) {
                idsite.getPersonnelList().remove(personnel);
                idsite = em.merge(idsite);
            }
            List<Evenement> evenementList = personnel.getEvenementList();
            for (Evenement evenementListEvenement : evenementList) {
                evenementListEvenement.setIdpersonnel(null);
                evenementListEvenement = em.merge(evenementListEvenement);
            }
            em.remove(personnel);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Personnel> findPersonnelEntities() {
        return findPersonnelEntities(true, -1, -1);
    }

    public List<Personnel> findPersonnelEntities(int maxResults, int firstResult) {
        return findPersonnelEntities(false, maxResults, firstResult);
    }

    private List<Personnel> findPersonnelEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Personnel.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Personnel findPersonnel(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Personnel.class, id);
        } finally {
            em.close();
        }
    }

    public int getPersonnelCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Personnel> rt = cq.from(Personnel.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
